#!/usr/bin/env python3
# -*- coding: utf-8 -*-
"""
GUI状态管理器
统一管理GUI组件的状态，减少重复代码
"""

import tkinter as tk
from tkinter import messagebox, filedialog
from enum import Enum


class ButtonState(Enum):
    """按钮状态枚举"""
    NORMAL = tk.NORMAL
    DISABLED = tk.DISABLED


class GUIStateManager:
    """GUI状态管理器"""
    
    def __init__(self):
        self.buttons = {}
        self.progress_var = None
        self.is_processing = False
    
    def register_button(self, name, button_widget):
        """注册按钮组件"""
        self.buttons[name] = button_widget
    
    def register_buttons(self, buttons_dict):
        """注册多个按钮组件"""
        for name, button in buttons_dict.items():
            self.register_button(name, button)
    
    def register_progress_var(self, progress_var):
        """注册进度变量"""
        self.progress_var = progress_var
    
    def set_button_state(self, button_name, state):
        """设置单个按钮状态"""
        if button_name in self.buttons:
            self.buttons[button_name].config(state=state.value)
    
    def set_buttons_state(self, button_names, state):
        """设置多个按钮状态"""
        for name in button_names:
            self.set_button_state(name, state)
    
    def set_all_buttons_state(self, state):
        """设置所有按钮状态"""
        for button in self.buttons.values():
            button.config(state=state.value)
    
    def disable_all_buttons(self):
        """禁用所有按钮"""
        self.set_all_buttons_state(ButtonState.DISABLED)
        self.is_processing = True
    
    def enable_all_buttons(self):
        """启用所有按钮"""
        self.set_all_buttons_state(ButtonState.NORMAL)
        self.is_processing = False
    
    def set_progress(self, message):
        """设置进度信息"""
        if self.progress_var:
            self.progress_var.set(message)
    
    def reset_progress(self):
        """重置进度信息"""
        if self.progress_var:
            self.progress_var.set("就绪")
    
    def start_creating_list_processing(self, message="正在处理..."):
        """开始处理状态"""
        self.disable_all_buttons()
        self.set_progress(message)
    
    def finish_processing(self):
        """完成处理状态"""
        self.enable_all_buttons()
        self.reset_progress()
    
    def set_processing_state(self, button_names, message):
        """设置特定处理状态"""
        self.set_buttons_state(button_names, ButtonState.DISABLED)
        self.set_progress(message)
        self.is_processing = True
    
    def finish_specific_processing(self, button_names):
        """完成特定处理状态"""
        self.set_buttons_state(button_names, ButtonState.NORMAL)
        self.reset_progress()
        self.is_processing = False


class DialogManager:
    """对话框管理器"""
    
    @staticmethod
    def show_info(title, message):
        """显示信息对话框"""
        messagebox.showinfo(title, message)

    @staticmethod
    def show_warning(title, message):
        """显示警告对话框"""
        messagebox.showwarning(title, message)

    @staticmethod
    def show_error(title, message):
        """显示错误对话框"""
        messagebox.showerror(title, message)

    @staticmethod
    def ask_yes_no(title, message):
        """显示是/否确认对话框"""
        return messagebox.askyesno(title, message)

    @staticmethod
    def select_folder(title="选择文件夹"):
        """选择文件夹对话框"""
        return filedialog.askdirectory(title=title)


class LogManager:
    """日志管理器"""
    
    def __init__(self, log_widget=None):
        self.log_widget = log_widget
        self.callbacks = []
    
    def register_log_widget(self, log_widget):
        """注册日志显示组件"""
        self.log_widget = log_widget
    
    def add_callback(self, callback):
        """添加日志回调函数"""
        self.callbacks.append(callback)
    
    def log(self, message):
        """记录日志"""
        # 显示在GUI组件中
        if self.log_widget:
            self.log_widget.insert(tk.END, message + '\n')
            self.log_widget.see(tk.END)
        
        # 调用回调函数
        for callback in self.callbacks:
            try:
                callback(message)
            except Exception:
                pass  # 忽略回调函数中的异常
        
        # 同时输出到控制台（调试用）
        print(message)
    
    def clear(self):
        """清空日志"""
        if self.log_widget:
            self.log_widget.delete(1.0, tk.END)


class ThreadManager:
    """线程管理器"""
    
    def __init__(self):
        self.active_threads = {}
    
    def start_thread(self, name, target, args=(), daemon=True):
        """启动新线程"""
        import threading
        
        # 如果同名线程已存在且仍在运行，则不启动新线程
        if name in self.active_threads and self.active_threads[name].is_alive():
            return False
        
        thread = threading.Thread(target=target, args=args, daemon=daemon)
        self.active_threads[name] = thread
        thread.start()
        return True
    
    def is_thread_running(self, name):
        """检查线程是否正在运行"""
        return name in self.active_threads and self.active_threads[name].is_alive()
    
    def wait_for_thread(self, name, timeout=None):
        """等待线程完成"""
        if name in self.active_threads:
            self.active_threads[name].join(timeout)
    
    def cleanup_finished_threads(self):
        """清理已完成的线程"""
        finished_threads = [name for name, thread in self.active_threads.items() 
                          if not thread.is_alive()]
        for name in finished_threads:
            del self.active_threads[name]
